package cn.edu.sjtu.se.randomfile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Random;

import sun.misc.BASE64Encoder;

public class RandomFile {

	private final static Random r = new Random();

	private int id;
	private byte[] b;
	private byte[] md5;

	public RandomFile(int size) {

		byte[] temp = new byte[size];
		r.nextBytes(temp);
		b = new BASE64Encoder().encode(temp).getBytes();
		id = r.nextInt();
		md5 = digest(b);
	}

	public String getName() {
		return "ID" + id;
	}

	public InputStream getInput() {
		return new ByteArrayInputStream(b);
	}

	public boolean checkMD5(byte[] b) {
		byte[] md5 = digest(b);
		return Arrays.equals(this.md5, md5);
	}

	public static byte[] digest(byte[] b) {
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");
			return md.digest(b);
		} catch (NoSuchAlgorithmException e) {
			return new byte[0];
		}
	}
}
